﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.WebPages;
using System.Web.Mvc;
using Telerik.Web.Mvc.UI;
using OBUCare.Core.Models;
using OBUCare.Core.Common;
using System.Web.Security;
using OBUCare.Core.BL;
using System.IO;
using OBUCare.Web.Models;
using OBUCare.Core.DataAccess;

namespace OBUCare.Web.Infrastructure
{
    public static class UIUtility
    {
        public static Exception GetInnermostException(this Exception exception)
        {
            while (exception.InnerException != null)
            {
                exception = GetInnermostException(exception.InnerException);
            }

            return exception;
        }

        /// <summary>
        /// 返回用@Html.checkbox创建的checkbox的值.用@Html.Checkbox方法创建的Checkbox在Html中默认加了一个Hidden
        /// </summary>
        /// <param name="rquest"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool GetCheckBoxValue(this HttpRequestBase rquest, string key)
        {
            bool? bv = false;
            var v = rquest.Form.GetValueByName(key);
            var array = v.Split(',');
            if (array.Length > 0)
                bv = array[0].ToBoolean();


            return bv.HasValue ? bv.Value : false;
        }

        public static string ToJsonString(this object value)
        {
            return new JavaScriptSerializer().Serialize(value);
        }

        public static bool Login(string uid, string pwd)
        {
            UserMgr mgr = new UserMgr();
            string clientIP = HttpContext.Current.Request.GetClientIpAddress();
            var u = mgr.Login(uid, pwd, clientIP);
            if (u != null)
            {
                AccessRightsMgr rMgr = new AccessRightsMgr(u);

                HttpContext.Current.Session["userInfo"] = u;
                HttpContext.Current.Session["AccessRightsMgr"] = rMgr;

                FormsAuthentication.SetAuthCookie(u.OPERATOR_NAME, false);
                return true;
            }
            else
                return false;
        }

        /// <summary>
        /// 检查是否有权限
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool CheckAccessRight(string url)
        {            
            var rMgr = HttpContext.Current.Session["AccessRightsMgr"] as AccessRightsMgr;
            if (rMgr == null)
            {
                return false;
            }
            else
                return rMgr.CheckAccessRight(url);
        }

        /// <summary>
        /// 返回登录后默认页
        /// </summary>
        /// <returns></returns>
        public static string GetDefaultPage()
        {
            var rMgr = HttpContext.Current.Session["AccessRightsMgr"] as AccessRightsMgr;
            if (rMgr == null)
            {
                return "/home";
            }
            else
            {
                return rMgr.GetDefaultPage();                    
            }
        }

        public static OPERATOR GetCurrentUser(this Controller controller)
        {
            return GetCurrentUser();
            //return controller.Session.GetCurrentUser();
        }


        public static OPERATOR GetCurrentUser()
        {
            var user = HttpContext.Current.Session["userInfo"] as OPERATOR;
            if (user == null)
            {
                if (!HttpContext.Current.Request.RawUrl.StartsWith("/home"))
                    HttpContext.Current.Response.Redirect("/home");
                //Login("000002", "1");
                //user = HttpContext.Current.Session["userInfo"] as OPERATOR;
            }
            return user;
        }

        /// <summary>
        /// 上传文件的临时目录
        /// </summary>
        /// <returns></returns>
        public static string GetTempFolderPath()
        {
            return HttpContext.Current.Server.MapPath("~/TemporaryFolder");
        }

        /// <summary>
        /// 获取模板文件路径
        /// </summary>
        /// <param name="template">模板的.xls</param>
        /// <returns></returns>
        public static string GetTemplateFilePath(string template)
        {
            return HttpContext.Current.Server.MapPath("~/Templates/" + template.Trim());
        }

        /// <summary>
        /// 获取模板文件路径
        /// </summary>
        /// <param name="template">模板的.xls</param>
        /// <returns></returns>
        public static string GetTemplateFilePath(this Controller c, string template)
        {
            return GetTemplateFilePath(template);
        }

        /// <summary>
        /// 删除昨天及之前生成的临时文件夹中的文件
        /// </summary>
        public static void RemoveFilesinTempFolder()
        {
            try
            {
                string tempFolder = GetTempFolderPath();
                Action a = () =>
                {
                    try
                    {
                        tempFolder.RemoveFiles(false, f =>
                        {
                            return DateTime.Today.AddDays(-1) > f.CreationTime;
                        });
                    }
                    catch (Exception e)
                    {

                    }
                };
                a.BeginInvoke(null, null);
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 左侧菜单配置
        /// </summary>
        /// <param name="page"></param>
        public static void ConfigSubMenu(this ViewStartPage page)
        {

            var con = page.ViewContext.RouteData.Values["controller"].ToString(); //获取该页面的controller名称

            OPERATOR o = UIUtility.GetCurrentUser();

            if (o == null)
                return;

            IEnumerable<ModuleFunctionViewModel> list = UIUtility.getModulFunctionParent(o);//获取主菜单
            if (list.Count() > 0)
            {
                IEnumerable<ModuleFunctionViewModel> listChild = UIUtility.getModulFunctionChild(o, "");//获取所有菜单

                var keyRoute = page.ViewContext.HttpContext.Request.Url.LocalPath;
                var r = (from i in listChild where i.ModuleURL == keyRoute select i); //根据关键信息在所有菜单中匹配出菜单
                if (r != null && r.Count() == 0)
                    r = (from i in list where i.ModuleURL == keyRoute select i);
                // var r = (from i in list where i.ParentID==all.ParentID select i);
                if (r != null && r.Count() > 0)
                {
                    var item = r.ToList().First();
                    page.PageData["moduleID"] = item.ModuleID;
                    string parentID = "";
                    if (item.ParentID != null && item.ParentID > 0)
                        parentID = item.ParentID.ToString();
                    else
                        parentID = item.ModuleID.ToString();

                    IEnumerable<ModuleFunctionViewModel> functionList = getModulFunctionChild(o, parentID);

                    page.PageData["SubMenu"] = functionList;
                }
            }
            //if ("#RepairOrders#".Contains("#" + con + "#") || "#Import#".Contains("#" + con + "#") || "#UserReceiveObu#".Contains("#" + con + "#"))
            //{
            //    //#RepairOrders# 里边以#隔开，记录使用RepairOrdersMenu这个左侧菜单的controller名称
            //    page.PageData["SubMenu"] = "RepairOrdersMenu";//维修单的左侧菜单，RepairOrdersMenu是个partial View，在View-》Shared 目录内
            //}
            //else if ("#Transfer#".Contains("#" + con + "#"))
            //{
            //    page.PageData["SubMenu"] = "TransferMenu";
            //}
            //else if ("#Transaction#".Contains("#" + con + "#") || "#Invoice#".Contains("#" + con + "#"))
            //{
            //    page.PageData["SubMenu"] = "TransactionMenu";
            //}

            ////else if ("#Invoice#".Contains("#" + con + "#"))
            ////{
            ////    page.PageData["SubMenu"] = "InvoiceMenu";
            ////}
            //else if ("#Report#".Contains("#" + con + "#"))
            //{
            //    page.PageData["SubMenu"] = "ReportMenu";
            //}
            //else if (con.ToLower() == "dicttype" || con.ToLower() == "dicttypevalues" || con.ToLower() == "partstype" || con.ToLower() == "repairtype")
            //{
            //    page.PageData["SubMenu"] = "dicttype";
            //}
            ////else
            ////page.PageData["SubMenu"] = con;
        }

        /// <summary>
        /// 获取跳转过来的模块号
        /// </summary>
        /// <param name="requestURL"></param>
        /// <returns></returns>
        public static string getMenuName(string requestURL)
        {
            string moduleID = "";
            OPERATOR o = UIUtility.GetCurrentUser();

            IEnumerable<ModuleFunctionViewModel> list = UIUtility.getModulFunctionParent(o);//获取主菜单
            if (list.Count() > 0)
            {
                IEnumerable<ModuleFunctionViewModel> listChild = UIUtility.getModulFunctionChild(o, "");//获取所有菜单

                var r = (from i in listChild where i.ModuleURL == requestURL select i); //根据关键信息在所有菜单中匹配出菜单
                if (r != null && r.Count() == 0)
                    r = (from i in list where i.ModuleURL == requestURL select i);
                // var r = (from i in list where i.ParentID==all.ParentID select i);
                if (r != null && r.Count() > 0)
                {
                    var item = r.ToList().First();
                    moduleID = item.ModuleID.ToString();

                }
            }
            return moduleID;
        }
        /// <summary>
        /// 获取主菜单
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static IEnumerable<ModuleFunctionViewModel> getModulFunctionParent(OPERATOR o)
        {
            try
            {
                string sql = "SELECT "
                + "DISTINCT OPERATOR_NO OperatorNO,C.MODULE_NAME OperatorName ,C.PARENT_ID ParentID,C.MODULE_INDEX ModuleIndex,"
                + " C.MODULE_LEVEL ModuleLevel,"
                + "C.MODULE_RIGHT ModuleRight,C.MODULE_URI ModuleURL,C.URI_MESSAGE ModuleMessage,C.ID ModuleID "
                + "FROM ISSUE_RPT.dbo.S_OPERATOR_ROLE AS A "
                + "JOIN ISSUE_RPT.dbo.S_ROLE_MODULE AS B ON A.ROLE_ID = B.ROLE_ID "
                + "JOIN ISSUE_RPT.dbo.S_MODULE_FUNCTION AS C ON B.MODULE_ID=C.ID "
                + "WHERE C.MODULE_LEVEL=0 AND C.PARENT_ID IS NULL AND C.ID>=12001 AND C.ID<=13000 AND C.MODULE_INDEX>=0 "
                + "AND  OPERATOR_NO='" + o.OPERATOR_NO + "' "
                + "ORDER BY A.OPERATOR_NO,C.MODULE_INDEX";
                return new OBU_CAREContext().Database.SqlQuery<ModuleFunctionViewModel>(sql).ToList();
            }
            catch (Exception)
            {

                throw;
            }

        }
        /// <summary>
        /// 根据父菜单获取所有子菜单
        /// </summary>
        /// <param name="o"></param>
        /// <param name="parentID"></param>
        /// <returns></returns>
        public static IEnumerable<ModuleFunctionViewModel> getModulFunctionChild(OPERATOR o, string parentID)
        {
            try
            {
                string where = parentID == "" ? "" : " AND PARENT_ID=" + parentID;
                // string whereChild = childID == "" ? "" : " AND C.ID='" + childID + "'";
                string sql = "SELECT "
                + "DISTINCT OPERATOR_NO OperatorNO,C.MODULE_NAME OperatorName ,C.PARENT_ID ParentID,C.MODULE_INDEX ModuleIndex,"
                + " C.MODULE_LEVEL ModuleLevel,"
                + "C.MODULE_RIGHT ModuleRight,C.MODULE_URI ModuleURL,C.URI_MESSAGE ModuleMessage,C.ID ModuleID "
                + "FROM ISSUE_RPT.dbo.S_OPERATOR_ROLE AS A  "
                + "JOIN ISSUE_RPT.dbo.S_ROLE_MODULE AS B ON A.ROLE_ID = B.ROLE_ID "
                + "JOIN ISSUE_RPT.dbo.S_MODULE_FUNCTION AS C ON B.MODULE_ID=C.ID "
                + "WHERE    C.ID>=12001 AND C.ID<=13000 AND MODULE_LEVEL=1  AND OPERATOR_NO='" + o.OPERATOR_NO + "' "
                + where
                + " ORDER BY A.OPERATOR_NO,C.MODULE_INDEX";
                return new OBU_CAREContext().Database.SqlQuery<ModuleFunctionViewModel>(sql).ToList();
            }
            catch (Exception)
            {

                throw;
            }

        }
        /// <summary>
        /// 根据第二级菜单的模块号 获取是否有营业厅的权限
        /// </summary>
        /// <param name="o"></param>
        /// <param name="modelID"></param>
        /// <returns></returns>
        public static IEnumerable<ModuleFunctionViewModel> getOnlyModuleByParent(OPERATOR o, string modelID)
        {
            try
            {
                string where = modelID == "" ? "" : " AND PARENT_ID=" + modelID;
                // string whereChild = childID == "" ? "" : " AND C.ID='" + childID + "'";
                string sql = "SELECT "
                + "DISTINCT OPERATOR_NO OperatorNO,C.MODULE_NAME OperatorName ,C.PARENT_ID ParentID,C.MODULE_INDEX ModuleIndex,"
                + " C.MODULE_LEVEL ModuleLevel,"
                + "C.MODULE_RIGHT ModuleRight,C.MODULE_URI ModuleURL,C.URI_MESSAGE ModuleMessage,C.ID ModuleID "
                + "FROM ISSUE_RPT.dbo.S_OPERATOR_ROLE AS A  "
                + "JOIN ISSUE_RPT.dbo.S_ROLE_MODULE AS B ON A.ROLE_ID = B.ROLE_ID "
                + "JOIN ISSUE_RPT.dbo.S_MODULE_FUNCTION AS C ON B.MODULE_ID=C.ID "
                + "WHERE    C.ID>=12001 AND C.ID<=13000 AND MODULE_LEVEL=2 AND OPERATOR_NO='" + o.OPERATOR_NO + "' "
                + where
                + " ORDER BY A.OPERATOR_NO,C.MODULE_INDEX";
                return new OBU_CAREContext().Database.SqlQuery<ModuleFunctionViewModel>(sql).ToList();
            }
            catch (Exception)
            {

                throw;
            }

        }
        /// <summary>
        /// 根据模块号 比对出营业厅权限
        /// </summary>
        /// <param name="moduleID"></param>
        /// <returns></returns>
        public static string getAgentByModule(OPERATOR operatorInfo, string moduleID)
        {
            string module = moduleID == null ? "" : moduleID.ToString();

            IEnumerable<ModuleFunctionViewModel> model = UIUtility.getOnlyModuleByParent(operatorInfo, module);
            int isAll = 0;
            if (model != null && model.Count() > 0)//如果配置了本营业厅或所有营业厅的权限则进行获取
            {
                model.Each(m =>
                {
                    if (Convert.ToInt16(m.ModuleURL) != isAll && Convert.ToInt16(m.ModuleURL) >= isAll)//如果获取的url较小 0为所有营业厅 6为本营业厅
                        isAll = Convert.ToInt16(m.ModuleURL);

                });
            }
            else  //如果没有配置 则默认为当前营业厅 也就是权限最小的
            {
                isAll = 6;
            }
            return isAll.ToString() == "0" ? "" : operatorInfo.AgentNo;
        }
        /// <summary>
        /// 获取操作员权限
        /// </summary>
        /// <param name="operatorInfo"></param>
        /// <param name="modelID"></param>
        /// <returns></returns>
        public static string getOperatorByModule(OPERATOR operatorInfo, int modelID)
        {
            IEnumerable<ModuleFunctionViewModel> listChild = UIUtility.getModulFunctionChild(operatorInfo, "");//获取所有菜单

            var r = (from i in listChild where i.ModuleID ==modelID select i); //根据关键信息在所有菜单中匹配出菜单

            IEnumerable<ModuleFunctionViewModel> models = UIUtility.getOnlyModuleByParent(operatorInfo,r.First().ModuleID.ToString());
            if (models != null && models.Count() > 0)
            {
                models = models.OrderBy(m=> m.ModuleURL); //获取最大权限

                return models.First().ModuleURL;
            }
            return "6";//0为所有营业厅权限 3为本营业厅负责人权限 6为本营业厅操作员权限 
        }
        public static IEnumerable<ModuleFunctionViewModel> toFunctionViewModel(IEnumerable<ModuleFunctionViewModel> functions)
        {
            try
            {
                var r = from log in functions
                        select toFunctionsViewModel(log);

                return r.ToList();

            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        public static ModuleFunctionViewModel toFunctionsViewModel(ModuleFunctionViewModel log)
        {
            ModuleFunctionViewModel m = new ModuleFunctionViewModel();

            m.OperatorNO = log.OperatorNO;
            m.OperatorName = log.OperatorName;
            m.ModuleURL = log.ModuleURL;
            m.ModuleID = log.ModuleID;
            m.ModuleIndex = log.ModuleIndex;
            m.ModuleLevel = log.ModuleLevel;
            m.ModuleMessage = log.ModuleMessage;
            m.ModuleRight = log.ModuleRight;
            return m;
        }
        /// <summary>
        /// 查询条件如果为全部，则转为null
        /// </summary>
        /// <param name="v"></param>
        /// <returns></returns>
        public static string ChangAllTextToNull(this string v)
        {
            if (UIConstants.AllItems.Equals(v))
                return null;
            else
                return v;
        }

        public static string View_PartsStockToString(this View_PartsStock item)
        {
            string r = item.Owner + UIConstants.Delimiter + item.PARTS_ID + UIConstants.Delimiter + item.PARTS_SPEC_ID + UIConstants.Delimiter + item.SUPPLIER_ID + UIConstants.Delimiter;
            return r;
        }

    }



    public static class OBUValidationHelper
    {
        const string requiredMsg = "*";
        const string digitsMsg = "只能为整数";
        const string numberMsg = "只能为数字";
        const string dateMsg = "日期格式不正确";
        const string rangeMsg = "只能介于 {0} 和 {1} 之间";
        const string maxlengthMsg = "输入长度最多是{0}的字符串";

        public static string GetValidationCssClass(bool required)
        {
            return GetValidationCssClass("", required);
        }

        public static string GetValidationCssClass(string fieldName, bool required)
        {
            return string.Format("{0}required:{2},messages:{0}required:'{3}'{1}{1}", "{", "}", required.getRequiredstring(), requiredMsg);
        }

        public static string GetValidationDigitsCssClass(string fieldName, bool required)
        {

            var temp = string.Format("{0}required:{2},digits:true,messages:{0}required:'{3}',digits:'{4}'{1}{1}", "{", "}", required.getRequiredstring(), requiredMsg, digitsMsg);
            return temp;

        }

        public static string GetValidationDigitsCssClass(string fieldName, bool required, int min, int max)
        {
            var rang = string.Format(rangeMsg, min, max);

            var temp = string.Format("{0}required:{2},digits:true,range:[{3},{4}],messages:{0}required:'{5}',digits:'{6}',range:'{7}'{1}{1}", "{", "}", required.getRequiredstring(), min, max, requiredMsg, digitsMsg, rang); //
            return temp;

        }

        public static string GetValidationNumberCssClass(string fieldName, bool required)
        {

            var temp = string.Format("{0}required:{2},number:true,messages:{0}required:'{3}',number:'{4}'{1}{1}", "{", "}", required.getRequiredstring(), requiredMsg, numberMsg);
            return temp;

        }

        public static string GetValidationNumberCssClass(string fieldName, bool required, double min, double max)
        {
            var rang = string.Format(rangeMsg, min, max);

            var temp = string.Format("{0}required:{2},number:true,range:[{3},{4}],messages:{0}required:'{5}',number:'{6}',range:'{7}'{1}{1}", "{", "}", required.getRequiredstring(), min, max, requiredMsg, numberMsg, rang); //
            return temp;

        }

        public static string GetValidationDateCssClass(string fieldName, bool required)
        {

            var temp = string.Format("{0}required:{2},dateISO:true,messages:{0}required:'{3}',dateISO:'{4}'{1}{1}", "{", "}", required.getRequiredstring(), requiredMsg, dateMsg);
            return temp;

        }

        public static string GetValidationStringCssClass(string fieldName, bool required, int maxlength)
        {
            var stringmaxLength = string.Format(maxlengthMsg, maxlength);

            var temp = string.Format("{0}required:{2},maxlength:{3},messages:{0}required:'{4}',maxlength:'{5}'{1}{1}", "{", "}", required.getRequiredstring(), maxlength, requiredMsg, stringmaxLength);
            return temp;

        }

        private static string getRequiredstring(this bool required)
        {
            var stringrequired = required ? "true" : "false";
            return stringrequired;
        }
    }

    public class ObuDropDownListHlper : IDisposable
    {

        private ConfigMgr configMgr = new ConfigMgr();

        //
        public IList<SelectListItem> GetDataSourcePart(string tblName,string AgentNo, bool isbindCode, object value, bool appendToEnd, params KeyValuePair<string, string>[] addionalItems)
        {
            List<SelectListItem> List = new List<SelectListItem>();
            IEnumerable<DICT_TYPE_VALUE> dbSource = null;
            if (!tblName.IsNullOrEmpty())
            {
                dbSource = configMgr.GetTypeValues(tblName).OrderBy(m => m.DICT_INDEX);
            }

            Action appendDbSource = () =>
            {
                
                dbSource.Each(i =>
                {
                    string selValue = isbindCode ? i.DICT_CODE : i.ID.ToText();
                    var selItem = new SelectListItem() { Value = selValue, Text = i.DICT_TITLE };
                    if (!AgentNo.IsNullOrEmpty())
                    {
                        if (i.DICT_TITLE.Contains("营业厅"))
                        {
                            List.Add(selItem);
                        }
                    }
                    else
                    { List.Add(selItem); }
                });
            };

            if (appendToEnd)
            {
                appendDbSource();
                bindAddionalItems(List, addionalItems);
            }
            else
            {
                bindAddionalItems(List, addionalItems);
                appendDbSource();
            }

            if (value != null)
            {
                var result = List.FirstOrDefault(v => v.Value.Equals(value.ToText()));

                if (result != null)
                { result.Selected = true; }
            }

            return List;
        }

        /// <summary>
        /// 返回用于绑定到DropDownList的数据库配置项目
        /// </summary>
        /// <param name="tblName">表名</param>
        /// <param name="isbindCode">是否绑定code,否：则绑定ID</param>
        /// <param name="value">默认选中项目</param>
        /// <param name="appendToEnd">是否将额外的项目绑定到尾部，否：绑定到头部</param>
        /// <param name="addionalItems">要额外的项目，key为value,value为Text</param>
        /// <returns></returns>
        public IList<SelectListItem> GetDataSource(string tblName, bool isbindCode, object value, bool appendToEnd, params KeyValuePair<string, string>[] addionalItems)
        {
            List<SelectListItem> List = new List<SelectListItem>();
            IEnumerable<DICT_TYPE_VALUE> dbSource = null;
            if (!tblName.IsNullOrEmpty())
            {
                dbSource = configMgr.GetTypeValues(tblName).OrderBy(m => m.DICT_INDEX);
            }

            Action appendDbSource = () =>
            {
                dbSource.Each(i =>
                    {
                        string selValue = isbindCode ? i.DICT_CODE : i.ID.ToText();
                        var selItem = new SelectListItem() { Value = selValue, Text = i.DICT_TITLE };
                        List.Add(selItem);
                    });
            };

            if (appendToEnd)
            {
                appendDbSource();
                bindAddionalItems(List, addionalItems);
            }
            else
            {
                bindAddionalItems(List, addionalItems);
                appendDbSource();
            }

            if (value != null)
            {
                var result = List.FirstOrDefault(v => v.Value.Equals(value.ToText()));

                if (result != null)
                { result.Selected = true; }
            }

            return List;
        }

        private void bindAddionalItems(IList<SelectListItem> List, params KeyValuePair<string, string>[] addionalItems)
        {
            addionalItems.Each(a =>
            {
                var selItem = new SelectListItem() { Value = a.Key, Text = a.Value };
                List.Add(selItem);
            });
        }

        public IList<SelectListItem> GetSuppliers(object value, bool appendToEnd, params KeyValuePair<string, string>[] addionalItems)
        {
            List<SelectListItem> List = new List<SelectListItem>();
            var dbItems = configMgr.GetSuppliers();

            Action appendDbSource = () =>
            {
                dbItems.Each(i =>
                {
                    var selItem = new SelectListItem() { Value = i.ID.ToString(), Text = i.SHORTNAME };
                    List.Add(selItem);
                });
            };

            if (appendToEnd)
            {
                appendDbSource();
                bindAddionalItems(List, addionalItems);
            }
            else
            {
                bindAddionalItems(List, addionalItems);
                appendDbSource();
            }

            if (value != null)
            {
                var result = List.FirstOrDefault(v => v.Value.Equals(value.ToText()));

                if (result != null)
                { result.Selected = true; }
            }

            return List;
        }

        public IList<SelectListItem> GetSpecs(object value, bool appendToEnd, int supplierID, params KeyValuePair<string, string>[] addionalItems)
        {
            List<SelectListItem> List = new List<SelectListItem>();
            try
            {
                var dbItems = new ISSUE_RPTContext().GetSpecs(supplierID);

                Action appendDbSource = () =>
                {
                    dbItems.Each(i =>
                    {
                        var selItem = new SelectListItem() { Value = i.ID.ToString(), Text = i.SPEC_NAME };
                        List.Add(selItem);
                    });
                };

                if (appendToEnd)
                {
                    appendDbSource();
                    bindAddionalItems(List, addionalItems);
                }
                else
                {
                    bindAddionalItems(List, addionalItems);
                    appendDbSource();
                }

                if (value != null)
                {
                    var result = List.FirstOrDefault(v => v.Value.Equals(value.ToText()));

                    if (result != null)
                    { result.Selected = true; }
                }

                return List;
            }
            catch (Exception ex)
            {
                
                throw ex;
            }

        }



        /// <summary>
        /// 获取厂商简称
        /// </summary>
        /// <param name="value"></param>
        /// <param name="appendToEnd"></param>
        /// <param name="addionalItems"></param>
        /// <returns></returns>
        public IList<SelectListItem> GetSuppliersShortName(object value, bool appendToEnd, params KeyValuePair<string, string>[] addionalItems)
        {
            List<SelectListItem> List = new List<SelectListItem>();
            var dbItems = configMgr.GetSuppliers();

            Action appendDbSource = () =>
            {
                dbItems.Each(i =>
                {
                    var selItem = new SelectListItem() { Value = i.SHORTNAME, Text = i.SHORTNAME };
                    List.Add(selItem);
                });
            };

            if (appendToEnd)
            {
                appendDbSource();
                bindAddionalItems(List, addionalItems);
            }
            else
            {
                bindAddionalItems(List, addionalItems);
                appendDbSource();
            }

            if (value != null)
            {
                var result = List.FirstOrDefault(v => v.Value.Equals(value.ToText()));

                if (result != null)
                { result.Selected = true; }
            }

            return List;
        }

        public IList<SelectListItem> GetAgents(object value, bool appendToEnd, string agentType, string agentNo, params KeyValuePair<string, string>[] addionalItems)
        {
            List<SelectListItem> List = new List<SelectListItem>();
            IList<AgentInfo> dbItems = null;

            if (agentType.IsNullOrEmpty()|| agentType.Equals(UIConstants.AllItems))
                dbItems = configMgr.GetAgents(agentNo);
            else
                dbItems = configMgr.GetAgents(agentNo).Where(c => c.Type == agentType).ToList();

            Action appendDbSource = () =>
            {
                dbItems.Each(i =>
                {
                    var selItem = new SelectListItem() { Value = i.AgentNo, Text = i.AgentName };
                    List.Add(selItem);
                });
            };

            if (appendToEnd)
            {
                appendDbSource();
                bindAddionalItems(List, addionalItems);
            }
            else
            {
                bindAddionalItems(List, addionalItems);
                appendDbSource();
            }

            if (value != null)
            {
                var result = List.FirstOrDefault(v => v.Value.Equals(value.ToText()));

                if (result != null)
                { result.Selected = true; }
            }

            return List;
        }

        public IList<SelectListItem> GetAgentTypes(object value, bool appendToEnd, string agentNo, params KeyValuePair<string, string>[] addionalItems)
        {
            List<SelectListItem> List = new List<SelectListItem>();
            var dbItems = configMgr.GetAgentTypes(agentNo);

            Action appendDbSource = () =>
            {
                dbItems.Each(i =>
                {
                    var selItem = new SelectListItem() { Value = i.Value, Text = i.Text };
                    List.Add(selItem);
                });
            };

            if (appendToEnd)
            {
                appendDbSource();
                bindAddionalItems(List, addionalItems);
            }
            else
            {
                bindAddionalItems(List, addionalItems);
                appendDbSource();
            }

            if (value != null)
            {
                var result = List.FirstOrDefault(v => v.Value.Equals(value.ToText()));

                if (result != null)
                { result.Selected = true; }
            }

            return List;
        }

        public IList<SelectListItem> GetOperators(object value, bool appendToEnd, params KeyValuePair<string, string>[] addionalItems)
        {
            List<SelectListItem> List = new List<SelectListItem>();
            var dbItems = configMgr.GetOPERATORS();

            Action appendDbSource = () =>
            {
                dbItems.Each(i =>
                {
                    var selItem = new SelectListItem() { Value = i.OPERATOR_NO, Text = i.OPERATOR_NAME };
                    List.Add(selItem);
                });
            };

            if (appendToEnd)
            {
                appendDbSource();
                bindAddionalItems(List, addionalItems);
            }
            else
            {
                bindAddionalItems(List, addionalItems);
                appendDbSource();
            }

            if (value != null)
            {
                var result = List.FirstOrDefault(v => v.Value.Equals(value.ToText()));

                if (result != null)
                { result.Selected = true; }
            }

            return List;
        }

        /// <summary>
        /// 获取配件型号配置
        /// </summary>
        /// <param name="value"></param>
        /// <param name="appendToEnd"></param>
        /// <param name="addionalItems"></param>
        /// <returns></returns>
        public IList<SelectListItem> GetPartsSpecs(object value, bool appendToEnd, params KeyValuePair<string, string>[] addionalItems)
        {
            List<SelectListItem> List = new List<SelectListItem>();
            var dbItems = this.configMgr.GetPartsSpecs();

            Action appendDbSource = () =>
            {
                dbItems.Each(i =>
                {
                    var selItem = new SelectListItem() { Value = i.ID.ToText(), Text = i.SPEC_NAME };
                    List.Add(selItem);
                });
            };

            if (appendToEnd)
            {
                appendDbSource();
                bindAddionalItems(List, addionalItems);
            }
            else
            {
                bindAddionalItems(List, addionalItems);
                appendDbSource();
            }

            if (value != null)
            {
                var result = List.FirstOrDefault(v => v.Value.Equals(value.ToText()));

                if (result != null)
                { result.Selected = true; }
            }

            return List;
        }
        /// <summary>
        /// 根据厂商获取配件型号配置
        /// </summary>
        /// <param name="value"></param>
        /// <param name="appendToEnd"></param>
        /// <param name="addionalItems"></param>
        /// <returns></returns>
        public IList<SelectListItem> GetPartsSpecs(object value,int supplierID, bool appendToEnd, params KeyValuePair<string, string>[] addionalItems)
        {
            List<SelectListItem> List = new List<SelectListItem>();
            IEnumerable<PARTS_SPECS> dbItems = null;
            if (supplierID.ToText()!="" && supplierID.ToText()!="0" && supplierID>0)
            {
                dbItems = this.configMgr.GetPartsSpecs(supplierID);
            }
            else 
            {
                dbItems = this.configMgr.GetPartsSpecs();
            }
           

            Action appendDbSource = () =>
            {
                dbItems.Each(i =>
                {
                    var selItem = new SelectListItem() { Value = i.ID.ToText(), Text = i.SPEC_NAME };
                    List.Add(selItem);
                });
            };

            if (appendToEnd)
            {
                appendDbSource();
                bindAddionalItems(List, addionalItems);
            }
            else
            {
                bindAddionalItems(List, addionalItems);
                appendDbSource();
            }

            if (value != null)
            {
                var result = List.FirstOrDefault(v => v.Value.Equals(value.ToText()));

                if (result != null)
                { result.Selected = true; }
            }

            return List;
        }
        /// <summary>
        /// 根据厂商、元器件获取型号配置信息
        /// </summary>
        /// <param name="value"></param>
        /// <param name="appendToEnd"></param>
        /// <param name="addionalItems"></param>
        /// <returns></returns>
        public IList<SelectListItem> GetPartsSpecs(object value, int supplierID,int partsType, bool appendToEnd, params KeyValuePair<string, string>[] addionalItems)
        {
            List<SelectListItem> List = new List<SelectListItem>();
            IEnumerable<PARTS_SPECS> dbItems = null;
            if (supplierID.ToText() != "" && supplierID.ToText() != "0" && supplierID > 0)
            {
                dbItems = this.configMgr.GetPartsSpecs(supplierID,partsType);
            }
            else
            {
                dbItems = this.configMgr.GetPartsSpecs();
            }


            Action appendDbSource = () =>
            {
                dbItems.Each(i =>
                {
                    var selItem = new SelectListItem() { Value = i.ID.ToText(), Text = i.SPEC_NAME };
                    List.Add(selItem);
                });
            };

            if (appendToEnd)
            {
                appendDbSource();
                bindAddionalItems(List, addionalItems);
            }
            else
            {
                bindAddionalItems(List, addionalItems);
                appendDbSource();
            }

            if (value != null)
            {
                var result = List.FirstOrDefault(v => v.Value.Equals(value.ToText()));

                if (result != null)
                { result.Selected = true; }
            }

            return List;
        }
        /// <summary>
        /// 获取配件型号配置状态下拉列表
        /// </summary>
        /// <param name="value"></param>
        /// <param name="appendToEnd"></param>
        /// <param name="agentNo"></param>
        /// <param name="addionalItems"></param>
        /// <returns></returns>
        public IList<SelectListItem> GetPartsSpecStatus(object value, bool appendToEnd, params KeyValuePair<string, string>[] addionalItems)
        {
            List<SelectListItem> List = new List<SelectListItem>();

            Action appendDbSource = () =>
            {                
                var selItem = new SelectListItem() { Value = DictTypeStatus.Normal.ToInt().ToText(), Text = "正常" };
                List.Add(selItem);
                selItem = new SelectListItem() { Value = DictTypeStatus.NotUsed.ToInt().ToText(), Text = "已作废" };
                List.Add(selItem);
            };

            if (appendToEnd)
            {
                appendDbSource();
                bindAddionalItems(List, addionalItems);
            }
            else
            {
                bindAddionalItems(List, addionalItems);
                appendDbSource();
            }

            if (value != null)
            {
                var result = List.FirstOrDefault(v => v.Value.Equals(value.ToText()));

                if (result != null)
                { result.Selected = true; }
            }

            return List;
        }

        /// <summary>
        /// 获取允许发行的配件类型
        /// </summary>
        /// <param name="value"></param>
        /// <param name="appendToEnd"></param>
        /// <param name="addionalItems"></param>
        /// <returns></returns>
        public IList<SelectListItem> GetPartTypes(object value, bool appendToEnd, params KeyValuePair<string, string>[] addionalItems)
        {
            List<SelectListItem> List = new List<SelectListItem>();
            var allItems = this.configMgr.GetPartsType();
            int status=DictTypeStatus.Normal.ToInt().Value ;
            var dbItems = from item in allItems
                          where item.ALLOWED_ISSUE && item.STATUS == status
                          select item;

            Action appendDbSource = () =>
            {
                dbItems.Each(i =>
                {
                    if (!ConfigMgr.OtherPartName.Equals(i.PARTS_NAME)) //如果是配件类型为其它，则忽略
                    {
                        var selItem = new SelectListItem() { Value = i.ID.ToText(), Text = i.PARTS_NAME };
                        List.Add(selItem);
                    }
                });
            };

            if (appendToEnd)
            {
                appendDbSource();
                bindAddionalItems(List, addionalItems);
            }
            else
            {
                bindAddionalItems(List, addionalItems);
                appendDbSource();
            }

            if (value != null)
            {
                var result = List.FirstOrDefault(v => v.Value.Equals(value.ToText()));

                if (result != null)
                { result.Selected = true; }
            }

            return List;
        }


        public IList<SelectListItem> GetOPERATORSByAgentNo(object menuNames,object value,string AgentNo, bool appendToEnd, params KeyValuePair<string, string>[] addionalItems)
        {
            List<SelectListItem> List = new List<SelectListItem>();
            var dbItems = configMgr.GetOPERATORSByAgentNo("");
            Action appendDbSource = () =>
            {
                dbItems.Each(i =>
                {
                    var selItem = new SelectListItem() { Value = i.OPERATOR_NO, Text = i.OPERATOR_NAME };
                    List.Add(selItem);
                });
            };

            if (appendToEnd)
            {
                appendDbSource();
                bindAddionalItems(List, addionalItems);
            }
            else
            {
                bindAddionalItems(List, addionalItems);
                appendDbSource();
            }
            OPERATOR operatorInfo = UIUtility.GetCurrentUser();
            string model = UIUtility.getOperatorByModule(operatorInfo, Convert.ToInt32(menuNames));

            switch (model)
            {
                case "0":
                case "3": //如果有所有营业厅和本营业厅负责人的权限 则结果集不变
                    break;
                case "6"://如果为本营业厅操作员的权限 则只绑定自己的名字
                    var selItem = new SelectListItem() { Value =operatorInfo.OPERATOR_NO, Text = operatorInfo.OPERATOR_NAME };
                    List.Clear();
                    List.Insert(0, selItem);
                    break;
                default:
                    var selItems = new SelectListItem() { Value =operatorInfo.OPERATOR_NO, Text = operatorInfo.OPERATOR_NAME };
                    List.Clear();
                    List.Insert(0, selItems);
                    break;

            }
            if (value != null && List.Count()>1)
            {
                var result = List.FirstOrDefault(v => v.Value.Equals(value.ToText()));

                if (result != null)
                { result.Selected = true; }
            }

            return List;
        }


        /// <summary>
        /// 获取配件划拨类型下拉列表
        /// </summary>
        /// <param name="value"></param>
        /// <param name="appendToEnd"></param>
        /// <param name="agentNo"></param>
        /// <param name="addionalItems"></param>
        /// <returns></returns>
        public IList<SelectListItem> GetPartsTransferKinds(object value, bool appendToEnd, params KeyValuePair<string, string>[] addionalItems)
        {
            List<SelectListItem> List = new List<SelectListItem>();

            Action appendDbSource = () =>
            {
                var selItem = new SelectListItem() { Value = Parts_Transfer_Kind.Transfer.ToInt().ToText(), Text = "划拨" };
                List.Add(selItem);
                selItem = new SelectListItem() { Value = Parts_Transfer_Kind.Change.ToInt().ToText(), Text = "调库" };
                List.Add(selItem);

                selItem = new SelectListItem() { Value = Parts_Transfer_Kind.Return.ToInt().ToText(), Text = "退库" };
                List.Add(selItem);

                selItem = new SelectListItem() { Value = Parts_Transfer_Kind.Reversal.ToInt().ToText(), Text = "冲正" };
                List.Add(selItem);
            };

            if (appendToEnd)
            {
                appendDbSource();
                bindAddionalItems(List, addionalItems);
            }
            else
            {
                bindAddionalItems(List, addionalItems);
                appendDbSource();
            }

            if (value != null)
            {
                var result = List.FirstOrDefault(v => v.Value.Equals(value.ToText()));

                if (result != null)
                { result.Selected = true; }
            }

            return List;
        }

     
        //public IList<SelectListItem> GetSellPartsPriceList(object value, bool appendToEnd, params KeyValuePair<string, string>[] addionalItems)
        //{
        //    List<SelectListItem> List = new List<SelectListItem>();
        //    var allItems = this.configMgr.GetPartsType();
        //    int status = DictTypeStatus.Normal.ToInt().Value;
        //    var dbItems = from item in allItems
        //                  where item.ALLOWED_ISSUE && item.STATUS == status
        //                  select item;

        //    Action appendDbSource = () =>
        //    {
        //        dbItems.Each(i =>
        //        {
        //            if (!ConfigMgr.OtherPartName.Equals(i.PARTS_NAME)) //如果是配件类型为其它，则忽略
        //            {
        //                var selItem = new SelectListItem() { Value = i.ID.ToText(), Text = i.PARTS_NAME };
        //                List.Add(selItem);
        //            }
        //        });
        //    };

        //    if (appendToEnd)
        //    {
        //        appendDbSource();
        //        bindAddionalItems(List, addionalItems);
        //    }
        //    else
        //    {
        //        bindAddionalItems(List, addionalItems);
        //        appendDbSource();
        //    }

        //    if (value != null)
        //    {
        //        var result = List.FirstOrDefault(v => v.Value.Equals(value.ToText()));

        //        if (result != null)
        //        { result.Selected = true; }
        //    }

        //    return List;
        //}

        /// <summary>
        /// 获取入库、冲正等下拉选项
        /// </summary>
        /// <param name="value"></param>
        /// <param name="appendToEnd"></param>
        /// <param name="agentNo"></param>
        /// <param name="addionalItems"></param>
        /// <returns></returns>
        public IList<SelectListItem> GetInStockBy(object value, bool appendToEnd, params KeyValuePair<string, string>[] addionalItems)
        {
            List<SelectListItem> List = new List<SelectListItem>();

            Action appendDbSource = () =>
            {
                var selItem = new SelectListItem() { Value = "1", Text = "正常入库" };
                List.Add(selItem);
                selItem = new SelectListItem() { Value = "2", Text = "入库被冲正" };
                List.Add(selItem);

                selItem = new SelectListItem() { Value ="3", Text = "入库冲正" };
                List.Add(selItem);
            };

            if (appendToEnd)
            {
                appendDbSource();
                bindAddionalItems(List, addionalItems);
            }
            else
            {
                bindAddionalItems(List, addionalItems);
                appendDbSource();
            }

            if (value != null)
            {
                var result = List.FirstOrDefault(v => v.Value.Equals(value.ToText()));

                if (result != null)
                { result.Selected = true; }
            }

            return List;
        }
        public void Dispose()
        {
            configMgr.Dispose();
        }
    }


    public class HelperPage : System.Web.WebPages.HelperPage
    {
        // Workaround - exposes the MVC HtmlHelper instead of the normal helper
        public static new HtmlHelper Html
        {
            get { return ((System.Web.Mvc.WebViewPage)WebPageContext.Current.Page).Html; }
        }
    }

   
}
